import React, { useContext, useEffect, useRef, useState } from 'react';
import { Button, Form, Popconfirm, Table } from 'antd';
import styles from "./src/style/xx-edit-table.module.scss";
import { EditInput, EditSelect, EditDatePicker } from './src/component';

const EditableContext = React.createContext(null);
const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    );
};
const EditableCell = ({ title,
    editable,
    TYPE,
    children,
    dataIndex,
    record,
    handleSave,
    props,
    ...restProps }) => {

    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
        if (editing) {
            inputRef.current.focus();
        }
    }, [editing]);
    const toggleEdit = () => {
        setEditing(!editing);
        form.setFieldsValue({
            [dataIndex]: record[dataIndex],
        });
    };
    const save = async () => {
        try {
            const values = await form.validateFields();
            toggleEdit();
            handleSave({
                ...record,
                ...values,
            });
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };
    let childNode = children;
    if (editable) {
        switch (TYPE) {
            case "Select": childNode = <EditSelect
                defaultValue={record[dataIndex]}
                editing={editing}
                dataIndex={dataIndex}
                title={title}
                inputRef={inputRef}
                save={save}
                toggleEdit={toggleEdit}
                children={children}
                {...props}
            />; break;
            case "DatePicker": childNode = <EditDatePicker
                defaultValue={record[dataIndex]}
                editing={editing}
                dataIndex={dataIndex}
                title={title}
                inputRef={inputRef}
                save={save}
                toggleEdit={toggleEdit}
                children={children}
            />; break;
            default: childNode = <EditInput
                editing={editing}
                dataIndex={dataIndex}
                title={title}
                inputRef={inputRef}
                save={save}
                toggleEdit={toggleEdit}
                children={children}

            />
        }



    }
    return <td {...restProps}>{childNode}</td>;
};

/**
 * @description 可编辑表格
 */
const XxEditable = ({ roleKey = 'id', defaultDataSource = [], onChange = null || Function, value, loading = true, ...props }) => {
    const [dataSource, setDataSource] = useState(defaultDataSource.map(item => ({
        ...item,
        data_temp_key: item[roleKey]
    })) || value || []);
    // const [count, setCount] = useState(0);
    const handleDelete = (keyValue) => {
        // console.log("要删除的", keyValue);
        const newData = dataSource.filter((item) => item.data_temp_key !== keyValue);
        setDataSource(newData);
    };

    useEffect(() => {
        return () => {
            setDataSource([]);
            // console.log("组件卸载");
        }
    }, [])

    // add newData object key
    const getObjectKyes = () => {
        if (props.addDefaultObject != null) {
            return props.addDefaultObject;
        } else {
            let object = {};
            const list = props.columns || [];
            list.forEach(item => {
                object[item.dataIndex] = null
            })
            return object;
        }

    }
    const objectKeys = getObjectKyes();

    useEffect(() => {
        onChange(dataSource);
    }, [dataSource])
    const defaultColumns = [
        ...props.columns,
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_, record) =>
                dataSource.length >= 1 ? (
                    <Popconfirm title="确认删除吗?" onConfirm={() => handleDelete(record.data_temp_key)}>
                        <a>删除</a>
                    </Popconfirm>
                ) : null,
        },
    ];
    const handleAdd = () => {
        // let length = dataSource.length + 1;
        const newData = {
            data_temp_key: new Date().getTime().toString(),
            ...objectKeys
        };

        setDataSource([...dataSource, newData]);
        // setCount(length);
    };

    // 点击保存事件 把所有数据展开给到newData，找到当前点击保存的。用新数据替换掉它。再重置下dataScource
    const handleSave = (row) => {
        // console.log("触发保存事件：", row);
        const newData = [...dataSource];
        const index = newData.findIndex((item) => row.data_temp_key === item.data_temp_key);
        const item = newData[index];

        newData.splice(index, 1, {
            ...item,
            ...row,
        });
        setDataSource(newData);
    };
    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };
    const useColumns = defaultColumns.map((col) => {
        // 如果editable 可以编辑 则返回col
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            // 否则 重新设置单元格属性 
            onCell: (record) => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                TYPE: col.TYPE,
                props: col.props || {},
                handleSave,
            }),
        };
    });

    return (
        <>
            <div className={styles.styles}>
                <Button
                    onClick={handleAdd}
                    type="primary"
                    style={{
                        marginBottom: 16,
                    }}
                >
                    添加
                </Button>
                {/* <Button
                    onClick={() => {
                        console.log("全部数据：\n", dataSource);
                    }}
                    type="primary"
                    style={{
                        marginBottom: 16,
                    }}
                >
                    打印数据
                </Button> */}
                <Table
                    loading={loading}
                    components={components}
                    rowClassName={() => 'editable-row'}
                    bordered
                    dataSource={dataSource}
                    columns={useColumns}
                />
            </div>

        </>
    )
}
export default XxEditable;